<template>
  <!-- 添加或修改盘点计划对话框 -->
  <el-dialog :title="title" v-model="open" width="1000px" append-to-body>
    <div style="padding: 20px; border-bottom: 1px solid #ccc">
      根据《中华人民共和国网络安全法》及相关法律的规定，用户需要提供真实身份信息，否则网络运营者不得为其提供相关服务。
      开发者实名认证信息资料填写规范如下：<br />
      1. 保证所填写的全部信息真实且与实际信息对应，否则出示驳回意见；<br />
      2.与入件资质相关字段填写正确，特别的：企业名称、统一社会信用代码、营业期限、法人代表人姓名、证件号码、证件有效期要与上传的证件照片保持一致，否则出示驳回意见；<br />
      3. 相关资质上传要求如下，如若不符，出示驳回意见。<br />
      1）图片清晰且边框完整；
    </div>
    <el-form
      ref="form"
      :inline="true"
      :model="form"
      :rules="rules"
      label-width="140px"
      style="padding-left: 10%; padding-top: 30px"
      v-loading="loading"
    >
      <el-form-item label="姓名:" prop="realName">
        <el-input v-model="form.realName" placeholder="请输入姓名"></el-input>
      </el-form-item>
      <el-form-item label="身份证号:" prop="identityCard">
        <el-input v-model="form.identityCard" placeholder="请输入身份证号"></el-input>
      </el-form-item>
      <el-row :gutter="20">
        <el-col :span="12" :offset="0">
          <el-form-item label="证件有效期:" required style="width: 100%">
            <el-date-picker
              :disabled="form.idCardLongStatus == '1'"
              @change="dateRangeChange"
              v-model="dateRange"
              type="daterange"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              :size="size"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12" :offset="0">
          <el-checkbox
            @change="dateChange"
            v-model="form.idCardLongStatus"
            :true-label="'1'"
            :false-label="'0'"
            style="margin-left: 10px"
            label="长期"
          ></el-checkbox>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="24" :offset="0">
          <el-form-item label="地址:" style="width: 100%" prop="country">
            <div style="display: flex; width: 100%">
              <el-cascader :options="options" v-model="form.country"> </el-cascader>
              <el-form-item style="width: 100%" prop="address">
                <el-input style="margin-left: 10px; width: 55%" v-model="form.address" placeholder="请输入详细地址"></el-input>
              </el-form-item>
            </div>
          </el-form-item>
        </el-col>
      </el-row>

      <el-form-item label="邮箱：" prop="email">
        <el-input v-model="form.email" placeholder="请输入邮箱"></el-input>
      </el-form-item>
      <!-- <el-form-item label="联系人手机号：" prop="lpMobil" placeholder="请输入联系人手机号">
        <el-input v-model="form.lpMobil"></el-input>
      </el-form-item> -->
      <!-- <el-form-item label="联系人邮箱：" prop="" placeholder="请输入联系人邮箱">
        <el-input v-model="form.corporationName"></el-input>
      </el-form-item> -->
      <!-- <el-form-item label="紧急手机号：" prop="urgencyMoblie" placeholder="请输入紧急手机号">
        <el-input v-model="form.urgencyMoblie"></el-input>
      </el-form-item> -->
      <el-row :gutter="20">
        <el-col :span="12" :offset="0">
          <el-form-item label="身份证正面：" prop="identityFront">
            <el-input v-model="form.identityFront" class="card-info-item" v-show="false"></el-input>
            <el-upload
              class="avatar-uploader el-upload"
              :headers="headers"
              accept="image/*"
              :on-success="(res, file) => handleUploadSuccess(res, file, 'identityFront')"
              :show-file-list="false"
              :action="uploadUrl"
            >
              <el-image fit="cover" v-if="form.identityFront" class="avatar" :src="form.identityFront" lazy>
                <template #error>
                  <div class="image-slot">
                    <img class="avatar" src="@/assets/goods/order/img_failure.svg" alt="" />
                  </div>
                </template>
              </el-image>
              <div v-else class="upload-text">点击上传图片</div>
              <div class="btn" v-if="form.identityFront">
                <el-button type="primary" @click.stop="deleteImg('identityFront')">
                  <el-icon>
                    <Delete />
                  </el-icon>
                </el-button>
              </div>
            </el-upload>
          </el-form-item>
        </el-col>
        <el-col :span="12" :offset="0">
          <el-form-item label="身份证反面：" prop="identityContrary">
            <el-input v-model="form.identityContrary" class="card-info-item" v-show="false"></el-input>
            <el-upload
              class="avatar-uploader el-upload"
              :headers="headers"
              accept="image/*"
              :on-success="(res, file) => handleUploadSuccess(res, file, 'identityContrary')"
              :show-file-list="false"
              :action="uploadUrl"
            >
              <el-image fit="cover" v-if="form.identityContrary" class="avatar" :src="form.identityContrary" lazy>
                <template #error>
                  <div class="image-slot">
                    <img class="avatar" src="@/assets/goods/order/img_failure.svg" alt="" />
                  </div>
                </template>
              </el-image>
              <div v-else class="upload-text">点击上传图片</div>
              <div class="btn" v-if="form.identityContrary">
                <el-button type="primary" @click.stop="deleteImg('identityContrary')">
                  <el-icon>
                    <Delete />
                  </el-icon>
                </el-button>
              </div>
            </el-upload>
          </el-form-item>
        </el-col>
      </el-row>
      <el-form-item label="手机：" prop="lpMobile">
        <el-input v-model="form.lpMobile" placeholder="请输入手机"></el-input>
      </el-form-item>
      <el-form-item label="验证码：" prop="smsCode">
        <el-input v-model="form.smsCode" auto-complete="off" placeholder="验证码">
          <template #append>
            <el-button type="primary" size="small" @click="handelSmsCaptcha">
              <span v-if="!smsState" class="active">获取验证码</span>
              <span v-else class="un-active">重新发送({{ times }})秒</span>
            </el-button>
          </template>
        </el-input>
      </el-form-item>
      <el-row :gutter="20"> </el-row>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="cancel">取 消</el-button>
        <el-button type="primary" @click="submitForm" :loading="loading">提交审核</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script>
import { globalHeaders } from '@/utils/request';
import { getSMSCode } from '@/api/login';
import * as Verify from '@/utils/verify';
import { addTenantAttestation, updateTenantAttestation } from '@/api/system/tenantAttestation';
import moment from 'moment';
import useUserStore from '@/store/modules/user';
const userStore = useUserStore();
import { provinceAndCityData, pcTextArr, regionData, pcaTextArr, codeToText } from 'element-china-area-data';

export default {
  name: 'personCertificate',
  data() {
    return {
      id: null, //必须配置，编辑需要赋值
      open: false,
      title: '填写认证信息',
      loading: false,
      form: {
        tenantType: 1
      },
      times: 60,
      defTimes: 60,
      smsState: false,
      dateRange: [],
      rules: {
        realName: [{ required: true, message: '姓名不能为空', trigger: 'blur' }],
        identityCard: [
          { required: true, message: '身份证号不能为空', trigger: 'blur' },
          { validator: this.isIDCard, trigger: 'blur' }
        ],
        country: [{ required: true, message: '请选择地址', trigger: 'change' }],
        address: [{ required: true, message: '详细地址不能为空', trigger: 'change' }],
        email: [
          { required: true, message: '请输入邮箱', trigger: 'blur' },
          { validator: this.isEmail, trigger: 'blur' }
        ],
        identityFront: [{ required: true, message: '请上传身份证正面', trigger: 'blur' }],
        identityContrary: [{ required: true, message: '请上传身份证反面', trigger: 'blur' }],
        lpMobile: [
          { required: true, message: '手机号不能为空', trigger: 'blur' },
          { validator: this.isPhone, trigger: 'blur' }
        ],
        smsCode: [{ required: true, message: '验证码不能为空', trigger: 'blur' }]
      },
      uploadUrl: import.meta.env.VITE_APP_BASE_API + '/resource/oss/upload',
      headers: globalHeaders(),
      options: regionData
    };
  },
  created() {
    console.log('codeToText :>> ', codeToText['110101']);
  },
  methods: {
    add(info) {
      this.open = true;
      this.dateRange = [];
      if (info.id) {
        this.form = { ...info };
        this.dateRange = [moment(this.form.identityStarttime), moment(this.form.identityEndtime)];
        this.form.country = (this.form.district || '').split(',');
      } else {
        this.form = { tenantType: 1 };
      }
      this.$nextTick(() => this.$refs.form.clearValidate());
    },
    cancel() {
      this.open = false;
    },
    handleUploadSuccess(res, file, key) {
      this.form[key] = res.data.url;
    },
    handleRemove(key) {
      this.form[key] = '';
    },
    beforeUpload(file) {
      const isJPG = file.type === 'image/jpeg' || file.type === 'image/png';
    },
    deleteImg(key) {
      this.form[key] = '';
    },
    submitForm() {
      console.log(this.form);
      this.form.district = this.form.country.join(',');
      this.$refs.form.validate((valid) => {
        if (valid) {
          if (!this.form.id) {
            addTenantAttestation({ ...this.form, tenantId: userStore.sysTenantVo.tenantId })
              .then((res) => {
                if (res.code == 200) {
                  this.$modal.msgSuccess('提交成功');
                  this.open = false;
                  this.$emit('ok');
                } else {
                  this.$modal.msgError('提交失败:' + res.msg);
                }
              })
              .catch(() => {});
          } else {
            updateTenantAttestation({ ...this.form, tenantId: userStore.sysTenantVo.tenantId })
              .then((res) => {
                if (res.code == 200) {
                  this.$modal.msgSuccess('提交成功');
                  this.open = false;
                  this.$emit('ok');
                } else {
                  this.$modal.msgError('提交失败:' + res.msg);
                }
              })
              .catch(() => {});
          }
        }
      });
    },
    // 请求发送短信验证码接口
    sendSmsCaptcha() {
      this.timer();
      getSMSCode({
        phonenumber: this.form.lpMobile
      })
        .then((result) => {
          console.log(result);
        })
        .catch(() => {})
        .finally(() => {});
    },
    handelSmsCaptcha() {
      if (!this.isLoading && !this.smsState && this.validteMobile(this.form.lpMobile || '')) {
        this.sendSmsCaptcha();
      }
    },
    validteMobile(str) {
      if (Verify.isEmpty(str)) {
        this.$modal.msgError('请先输入手机号');
        return false;
      }
      if (!Verify.isMobile(str)) {
        this.$modal.msgError('请输入正确格式的手机号');
        return false;
      }
      return true;
    },
    // 执行定时器
    timer() {
      this.smsState = true;
      const inter = setInterval(() => {
        this.times = this.times - 1;
        if (this.times <= 0) {
          this.smsState = false;
          this.times = this.defTimes;
          clearInterval(inter);
        }
      }, 1000);
    },
    isIDCard(rule, value, callback) {
      console.log('Verify :>> ', typeof Verify.isIDCard);
      console.log('Verify.isIDCard(value) :>> ', Verify);
      if (!value) {
        return callback(new Error('身份证不能为空'));
      } else if ((value.length !== 18 && value.length !== 15) || !Verify.isIDCard(value)) {
        callback(new Error('请输入正确的身份证号码'));
      } else {
        callback();
      }
    },
    isEmail(rule, value, callback) {
      if (!value) {
        return callback(new Error('邮箱不能为空'));
      } else if (value.length > 50 || !Verify.isEmail(value)) {
        callback(new Error('请输入正确的邮箱格式'));
      } else {
        callback();
      }
    },
    isPhone(rule, value, callback) {
      if (!value) {
        callback(new Error('请输入正确的手机号'));
      } else if (value.length !== 11 || !Verify.isMobile(value)) {
        callback(new Error('请输入正确的手机号'));
      }
      callback();
    },

    dateRangeChange(val) {
      if (val.length) {
        this.form.identityStarttime = val[0];
        this.form.identityEndtime = val[1];
      } else {
        this.form.identityStarttime = null;
        this.form.identityEndtime = null;
        this.dateRange = [];
      }
    },
    dateChange(val) {
      if (val == '1') {
        this.dateRangeChange([]);
      }
    }
  }
};
</script>

<style lang="scss" scoped>
.container {
  padding: 20px;
}

.mark {
  width: 18px;
  margin-right: 10px;
}

.avatar-uploader,
.el-upload {
  border: 1px solid #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  width: 120px !important;
  height: 120px;
  // display: inline-block;
  margin-right: 10px;
}

.avatar-uploader:hover,
.el-upload:hover {
  border-color: #409eff;
}

.imgs {
  display: inline-block;
}

.avatar-uploader__img {
  border: 1px solid #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  width: 120px !important;
  height: 120px;
  display: inline-block;
  margin-right: 10px;

  img {
    width: 120px !important;
    height: 120px;
    object-fit: fill;
  }
}

.btn {
  display: none;
  position: absolute;
  top: 0;
  right: 0;
  background-color: rgba(0, 0, 0, 0.5);
  color: #fff;
  width: 120px !important;
  height: 120px;
  border-radius: 0 6px 0 6px;
  text-align: center;
  line-height: 120px;
}

.avatar-uploader:hover {
  // 鼠标悬浮显示按钮
  .btn {
    display: block;
  }
}

.upload-text {
  font-size: 14px;
  color: #8c939d;
  line-height: 20px;
  text-align: center;
  margin: 0 auto;
}

.avatar {
  width: 120px;
  height: 120px;
  display: block;
}

.card-info-item {
  width: 450px;
}

.content-img {
  display: flex;
  padding-top: 40px;
  // justify-content: space-between;
}

.card {
  margin-top: 20px;
}

.form-item__label::before {
  content: '*';
  color: #f56c6c;
  margin-right: 4px;
}

.active {
  color: #409eff;
}

.un-active {
  color: #c0c4cc;
}
</style>